<template>
  <div class="editor-header">
    <div class="left">
      <lzc-file-picker ref="fileShared" base-url="/_lzc/files/home"
        accept="*.pptx, *.pptist, application/vnd.openxmlformats-officedocument.presentationml.presentation"
        type="file" title="选择网盘文件" confirm-button-title="打开" @visible="showLzcFilePicker = false"
        @submit="submitLzcFilePicker">
      </lzc-file-picker>
      <Dropdown :trigger="['click']">
        <div class="menu-item"><IconFolderClose /> <span class="text">文件</span></div>
        <template #overlay>
          <Menu>

            <div>
              <MenuItem @click="showLzcFilePicker = true">导入网盘文件</MenuItem>
            </div>

            <FileInput accept=".pptist"  @change="files => importSpecificFile(files)">
              <MenuItem>导入 pptist 文件</MenuItem>
            </FileInput>
            <FileInput accept="application/vnd.openxmlformats-officedocument.presentationml.presentation"  @change="files => importPPTXFile(files)">
              <MenuItem>导入 pptx 文件（demo）</MenuItem>
            </FileInput>
            <MenuItem @click="setDialogForExport('pptx')">导出文件</MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['click']">
        <div class="menu-item"><IconEdit /> <span class="text">编辑</span></div>
        <template #overlay>
          <Menu>
            <MenuItem @click="undo()">撤销</MenuItem>
            <MenuItem @click="redo()">重做</MenuItem>
            <MenuItem @click="createSlide()">添加页面</MenuItem>
            <MenuItem @click="deleteSlide()">删除页面</MenuItem>
            <MenuItem @click="toggleGridLines()">{{ gridLineSize ? '关闭网格线' : '打开网格线' }}</MenuItem>
            <MenuItem @click="toggleRuler()">{{ showRuler ? '关闭标尺' : '打开标尺' }}</MenuItem>
            <MenuItem @click="resetSlides()">重置幻灯片</MenuItem>
            <MenuItem @click="openSelectPanel()">{{ showSelectPanel ? '关闭选择面板' : '打开选择面板' }}</MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['click']">
        <div class="menu-item"><IconPpt /> <span class="text">演示</span></div>
        <template #overlay>
          <Menu>
            <MenuItem @click="enterScreeningFromStart()">从头开始</MenuItem>
            <MenuItem @click="enterScreening()">从当前页开始</MenuItem>
          </Menu>
        </template>
      </Dropdown>
      <Dropdown :trigger="['click']">
        <div class="menu-item"><IconHelpcenter /> <span class="text">帮助</span></div>
        <template #overlay>
          <Menu>
            <MenuItem @click="goLink('https://github.com/pipipi-pikachu/PPTist/issues')">意见反馈</MenuItem>
            <MenuItem @click="goLink('https://github.com/pipipi-pikachu/PPTist/blob/master/doc/Q&A.md')">常见问题</MenuItem>
            <MenuItem @click="hotkeyDrawerVisible = true">快捷键</MenuItem>
          </Menu>
        </template>
      </Dropdown>
    </div>

    <div class="right">
      <Tooltip :mouseLeaveDelay="0" title="导出">
        <div class="menu-item" @click="setDialogForExport('pptx')">
          <IconShare size="18" fill="#666" />
        </div>
      </Tooltip>
      <Tooltip :mouseLeaveDelay="0" title="幻灯片放映">
        <div class="menu-item" @click="enterScreening()">
          <IconPpt size="19" fill="#666" style="margin-top: 1px;" />
        </div>
      </Tooltip>
      <a href="https://github.com/pipipi-pikachu/PPTist" target="_blank">
        <div class="menu-item"><IconGithub size="18" fill="#666" /></div>
      </a>
    </div>

    <Drawer
      width="320"
      placement="right"
      :closable="false"
      :visible="hotkeyDrawerVisible"
      @close="hotkeyDrawerVisible = false"
    >
      <HotkeyDoc />
    </Drawer>

    <FullscreenSpin :loading="exporting" tip="正在导入..." />
  </div>
</template>

<script lang="ts" setup>
import { ref, nextTick, watch, onMounted } from 'vue'
import { storeToRefs } from 'pinia'
import { useMainStore } from '@/store'
import useScreening from '@/hooks/useScreening'
import useSlideHandler from '@/hooks/useSlideHandler'
import useHistorySnapshot from '@/hooks/useHistorySnapshot'
import useImport from '@/hooks/useImport'
import useHomeCloud from '@/hooks/useHomeCloud'

import HotkeyDoc from './HotkeyDoc.vue'
import FileInput from '@/components/FileInput.vue'
import FullscreenSpin from '@/components/FullscreenSpin.vue'
import {
  Tooltip,
  Dropdown,
  Menu,
  Drawer,
  message,
} from 'ant-design-vue'
const MenuItem = Menu.Item

const mainStore = useMainStore()
const { gridLineSize, showRuler, showSelectPanel } = storeToRefs(mainStore)

const { enterScreening, enterScreeningFromStart } = useScreening()
const { createSlide, deleteSlide, resetSlides, focusLastSlide } = useSlideHandler()
const { redo, undo } = useHistorySnapshot()
const { loadHomeCloud } = useHomeCloud()
const { importSpecificFile, importPPTXFile, exporting } = useImport()

const setDialogForExport = mainStore.setDialogForExport

const toggleGridLines = () => {
  mainStore.setGridLineSize(gridLineSize.value ? 0 : 50)
}

const toggleRuler = () => {
  mainStore.setRulerState(!showRuler.value)
}

const openSelectPanel = () => {
  if (!showSelectPanel.value) mainStore.setSelectPanelState(true)
  else mainStore.setSelectPanelState(false)
}

const hotkeyDrawerVisible = ref(false)

const goLink = (url: string) => window.open(url)

const fileShared = ref()

onMounted(async () => {
  const url = new URL(window.location.href)
  const file = url.searchParams.get('file')
  if (file && file.length > 1) {
    message.loading('正在导入……', 3)
    focusLastSlide()
    await importLzcFile(file)
  }
  showLzcFilePicker.value = false
})

const importLzcFile = async (filename: string) => {
  const response = await loadHomeCloud(`/_lzc/files/home/${filename}`)

  if (filename.endsWith('.pptist')) {
    const blob: Blob = await response.blob()
    importSpecificFile(webdavFileToFileList(blob, filename))
  }
  else if (filename.endsWith('.pptx')) {
    const blob: Blob = await response.blob()
    importPPTXFile(webdavFileToFileList(blob, filename))
  }
}

// 网盘文件选择，以导入
// 支持 pptist 和 pptx 文件格式
const showLzcFilePicker = ref(false)
const submitLzcFilePicker = async (e: CustomEvent) => {
  const file = dataTransfer<FileStat>(e)
  if (file) {
    await importLzcFile(file.filename)
  }
  showLzcFilePicker.value = false
}

const webdavFileToFileList = (webdavFile: Blob, fileName: string): FileList => {
  const file = new File([webdavFile], fileName)
  const dataTransfer = new DataTransfer()
  dataTransfer.items.add(file)
  return dataTransfer.files
}

async function invoke(instance: any, method: string, ...args: string[]) {
  await nextTick()
  const exposed = instance.value._instance.exposed
  !!exposed[method] && exposed[method](...args)
}
watch(showLzcFilePicker, (newVal) => {
  if (newVal) {
    invoke(fileShared, 'init')
    invoke(fileShared, 'open')
  }
  else {
    invoke(fileShared, 'close')
  }
})
function dataTransfer<T>(raw: any) {
  if (!raw) return
  const output = raw.detail[0]
  return output as T
}
interface FileStat {
  filename: string;
  basename: string;
  lastmod: string;
  size: number;
  type: 'file' | 'directory';
  etag: string | null;
  mime?: string;
  props?: DAVResultResponseProps;
}
interface DAVResultResponseProps {
  displayname: string;
  resourcetype: {
    collection?: boolean;
  };
  getlastmodified?: string;
  getetag?: string;
  getcontentlength?: string;
  getcontenttype?: string;
  'quota-available-bytes'?: any;
  'quota-used-bytes'?: string;
}
</script>

<style lang="scss" scoped>
.editor-header {
  background-color: #fff;
  user-select: none;
  border-bottom: 1px solid $borderColor;
  display: flex;
  justify-content: space-between;
  padding: 0 10px;
}
.left, .right {
  display: flex;
  justify-content: center;
  align-items: center;
}
.menu-item {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 14px;
  padding: 0 10px;
  cursor: pointer;

  .text {
    margin-left: 4px;
  }
}

.left .menu-item:hover {
  background-color: #f9f9f9;
}
</style>